# -*- coding: utf-8 -*-
#	Copyright 2005,2006,2007,2008 Spike^ekipS <spikeekips@gmail.com>
#
#	   This program is free software; you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation; either version 2 of the License, or
#	(at your option) any later version.
#
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with this program; if not, write to the Free Software
#	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

from django.db.models.query import QuerySet, EmptyQuerySet, insert_query
from django.db import models, connection
from django.db.models import Q, ObjectDoesNotExist

from search.lucene_to_django_model.models.sql.query import Query
from search import pylucene
import search as django_searcher

class QuerySetSearcher (QuerySet) :
	_fields = list()
	_kind = None
	_order = None
	_in_bulk = False
	flat = False

	def __init__ (self, model=None, query=None, ) :
		super(QuerySetSearcher, self).__init__(model=model, query=query)
		self.query = query or Query(self.model, connection)

	def __repr__(self) :
		return repr(list(self))

	def _clone (self, *args, **kwargs) :
		if self.flat : kwargs.update({"flat": self.flat})
		if self._fields : kwargs.update({"_fields": self._fields})
		if self._kind : kwargs.update({"_kind": self._kind})
		if self._order : kwargs.update({"_order": self._order})
		if self._in_bulk : kwargs.update({"_in_bulk": self._in_bulk})

		return super(QuerySetSearcher, self)._clone(*args, **kwargs)

	def __len__(self) :
		if self._result_cache is None:
			if self._iter:
				self._result_cache = list(self._iter)
			else:
				self._result_cache = list(self.iterator())
		elif self._iter:
			self._result_cache.extend(list(self._iter))

		return len(self._result_cache)

	def raw (self, query) :
		try :
			query = pylucene.parse_query(query)
		except :
			return self

		clone = self._clone()
		clone.query.add_raw_query(query)
		return clone

	def iterator (self) :
		for row in self.query.results_iter() :
			row = django_searcher.DocumentObject(self.model, row, queryset=self)
			if self._fields :
				if self.flat :
					if self._kind :
						yield map(lambda x: row[x], self._fields)[0]
					else :
						yield tuple(map(lambda x: row[x], self._fields))
				else :
					yield dict(map(lambda x: (x, row[x]), self._fields))
			else :
				yield row

	def values (self, *fields) :
		return self._clone(klass=QuerySetSearcher, setup=True, _fields=fields)

	def values_list (self, *fields) :
		return self._clone(klass=QuerySetSearcher, setup=True, _fields=fields, flat=True, )

	def dates (self, field_name, kind, order="ASC") :
		return self._clone(klass=QuerySetSearcher, setup=True, _fields=[field_name, ], _kind=kind, _order=order, flat=True, )

	def in_bulk (self, pk_list) :
		o = self.filter(**{"%s__in" % self.model._meta.pk.name: pk_list})
		r = list()
		for i in o :
			r.append((i.get("__pk__"), i))

		return dict(r)

	def latest (self, field_name=None) :
		latest_by = field_name or self.model._meta.get_latest_by
		obj = self._clone()
		obj.query.set_limits(high=1)
		obj.query.add_ordering("-%s" % latest_by, "-__pk__", )
		return obj.get()

	def get (self, *args, **kwargs) :
		if kwargs.has_key("pk") :
			searcher = pylucene.Searcher()
			doc = searcher.get_document_by_uid(django_searcher.get_uid(self.model, kwargs.get("pk")))
			if doc is None :
				raise ObjectDoesNotExist, ""

			return django_searcher.DocumentObject(self.model, doc)

		return super(QuerySetSearcher, self).get(*args, **kwargs)

	def __return_blank_list (self, *args, **kwargs) :
		return list()

	select_related = __return_blank_list
	extra = __return_blank_list

	def __not_implemented (self, *args, **kwargs) :
		raise Exception, NotImplemented

	create = __not_implemented
	get_or_create = __not_implemented

"""
Description
-----------


ChangeLog
---------


Usage
-----


"""

__author__ =  "Spike^ekipS <spikeekips@gmail.com>"




